<template>
  <div class="workstation-report">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>工位生产报表</span>
          <div class="header-actions">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleDateChange"
            />
            <el-button type="primary" @click="refreshReport">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 统计卡片 -->
      <div class="stats-section">
        <el-row :gutter="20">
          <el-col :span="6" v-for="report in reportData" :key="report.workstationId">
            <el-card class="stats-card" shadow="hover">
              <div class="stats-content">
                <div class="stats-header">
                  <h3>{{ report.workstationName }}</h3>
                  <el-tag type="success">{{ report.reportDate }}</el-tag>
                </div>
                <div class="stats-body">
                  <div class="stat-item">
                    <div class="stat-value">{{ report.totalInCount }}</div>
                    <div class="stat-label">进站数量</div>
                  </div>
                  <div class="stat-item">
                    <div class="stat-value">{{ report.totalOutCount }}</div>
                    <div class="stat-label">出站数量</div>
                  </div>
                  <div class="stat-item">
                    <div class="stat-value">{{ report.qualificationRate.toFixed(1) }}%</div>
                    <div class="stat-label">合格率</div>
                  </div>
                  <div class="stat-item">
                    <div class="stat-value">{{ report.utilizationRate.toFixed(1) }}%</div>
                    <div class="stat-label">利用率</div>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 图表区域 -->
      <div class="charts-section">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card shadow="hover">
              <template #header>
                <span>小时产量趋势</span>
              </template>
              <div ref="hourlyChartRef" style="height: 300px;"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card shadow="hover">
              <template #header>
                <span>工位效率对比</span>
              </template>
              <div ref="efficiencyChartRef" style="height: 300px;"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 详细数据表格 -->
      <div class="table-section">
        <el-card shadow="hover">
          <template #header>
            <span>详细数据</span>
          </template>
          <el-table :data="reportData" stripe>
            <el-table-column prop="workstationName" label="工位名称" width="120" />
            <el-table-column prop="totalInCount" label="进站数量" width="100" />
            <el-table-column prop="totalOutCount" label="出站数量" width="100" />
            <el-table-column prop="qualifiedCount" label="合格数量" width="100" />
            <el-table-column prop="unqualifiedCount" label="不合格数量" width="120" />
            <el-table-column prop="qualificationRate" label="合格率" width="100">
              <template #default="{ row }">
                {{ row.qualificationRate.toFixed(1) }}%
              </template>
            </el-table-column>
            <el-table-column prop="avgProcessingDuration" label="平均加工时长(分)" width="150">
              <template #default="{ row }">
                {{ row.avgProcessingDuration.toFixed(1) }}
              </template>
            </el-table-column>
            <el-table-column prop="utilizationRate" label="利用率" width="100">
              <template #default="{ row }">
                {{ row.utilizationRate.toFixed(1) }}%
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="WorkstationReport">
import { ref, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { Refresh } from "@element-plus/icons-vue";
import * as echarts from "echarts";
import * as WorkstationOperationApi from "@/api/modules/workstationOperation";

// 日期范围
const dateRange = ref<[string, string]>([
  new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
  new Date().toISOString().split('T')[0]
]);

// 报表数据
const reportData = ref<WorkstationOperationApi.WorkstationOperation.ReportData[]>([]);

// 图表引用
const hourlyChartRef = ref<HTMLDivElement>();
const efficiencyChartRef = ref<HTMLDivElement>();

// 图表实例
let hourlyChart: echarts.ECharts;
let efficiencyChart: echarts.ECharts;

// 日期变化处理
const handleDateChange = (dates: [string, string]) => {
  if (dates && dates.length === 2) {
    refreshReport();
  }
};

// 刷新报表
const refreshReport = async () => {
  try {
    const params = {
      startDate: dateRange.value[0],
      endDate: dateRange.value[1]
    };
    
    const { data } = await WorkstationOperationApi.getWorkstationReport(params);
    reportData.value = data;
    
    // 更新图表
    await nextTick();
    updateCharts();
  } catch (error) {
    ElMessage.error("获取报表数据失败");
    console.error("获取报表数据失败:", error);
  }
};

// 初始化图表
const initCharts = () => {
  if (hourlyChartRef.value) {
    hourlyChart = echarts.init(hourlyChartRef.value);
  }
  if (efficiencyChartRef.value) {
    efficiencyChart = echarts.init(efficiencyChartRef.value);
  }
};

// 更新图表
const updateCharts = () => {
  if (reportData.value.length === 0) return;

  // 小时产量趋势图
  if (hourlyChart && reportData.value[0]?.hourlyProduction) {
    const hours = reportData.value[0].hourlyProduction.map(item => `${item.hour}:00`);
    const series = reportData.value.map(report => ({
      name: report.workstationName,
      type: 'line',
      data: report.hourlyProduction.map(item => item.outCount)
    }));

    hourlyChart.setOption({
      title: {
        text: '小时产量趋势',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        bottom: 0
      },
      xAxis: {
        type: 'category',
        data: hours
      },
      yAxis: {
        type: 'value',
        name: '产量'
      },
      series: series
    });
  }

  // 工位效率对比图
  if (efficiencyChart) {
    const workstationNames = reportData.value.map(item => item.workstationName);
    const utilizationRates = reportData.value.map(item => item.utilizationRate);
    const qualificationRates = reportData.value.map(item => item.qualificationRate);

    efficiencyChart.setOption({
      title: {
        text: '工位效率对比',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        bottom: 0
      },
      xAxis: {
        type: 'category',
        data: workstationNames
      },
      yAxis: {
        type: 'value',
        name: '百分比(%)'
      },
      series: [
        {
          name: '利用率',
          type: 'bar',
          data: utilizationRates,
          itemStyle: {
            color: '#5470c6'
          }
        },
        {
          name: '合格率',
          type: 'bar',
          data: qualificationRates,
          itemStyle: {
            color: '#91cc75'
          }
        }
      ]
    });
  }
};

// 窗口大小变化时重新调整图表
const handleResize = () => {
  hourlyChart?.resize();
  efficiencyChart?.resize();
};

onMounted(async () => {
  await refreshReport();
  await nextTick();
  initCharts();
  updateCharts();
  
  window.addEventListener('resize', handleResize);
});
</script>

<style scoped lang="scss">
.workstation-report {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-actions {
      display: flex;
      gap: 10px;
      align-items: center;
    }
  }

  .stats-section {
    margin-bottom: 20px;

    .stats-card {
      .stats-content {
        .stats-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 15px;

          h3 {
            margin: 0;
            font-size: 16px;
          }
        }

        .stats-body {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 10px;

          .stat-item {
            text-align: center;

            .stat-value {
              font-size: 24px;
              font-weight: bold;
              color: #409eff;
              margin-bottom: 5px;
            }

            .stat-label {
              font-size: 12px;
              color: #666;
            }
          }
        }
      }
    }
  }

  .charts-section {
    margin-bottom: 20px;
  }

  .table-section {
    .el-table {
      margin-top: 10px;
    }
  }
}
</style>